//
//  MainViewController.swift
//  Weibo
//
//  Created by 杨雨哲 on 15/6/23.
//  Copyright © 2015年 yyz. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tb = MainTabBar()
        
        setValue(tb, forKeyPath: "tabBar")
        
        tb.compoesButton.addTarget(self, action: "composedButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        addChildViewControllers()

        // Do any additional setup after loading the view.
    }
    
    func composedButtonClicked(){
        print(__FUNCTION__)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private func addChildViewControllers() {
        
        let url = NSBundle.mainBundle().URLForResource("MainVcSettings", withExtension: "json")!
        
        let data = NSData(contentsOfURL: url)!
        
        do{
            let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            
            for dict in array as! [[String:String]]{
                
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            }
        }catch{
            print(error)
            addChildViewController("HomeViewController", title: "首页", imageName: "tabbar_home")
            addChildViewController("MessageViewController", title: "消息", imageName: "tabbar_message_center")
            addChildViewController("DiscoverViewController", title: "发现", imageName: "tabbar_discover")
            addChildViewController("ProfileViewController", title: "我", imageName: "tabbar_profile")
        }
    }
    
    private func addChildViewController(vcName:String,title:String,imageName:String) {
        
        
        let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        
        let cls: AnyClass = NSClassFromString(ns + "." + vcName)!
        
        let vc = cls.new() as! UIViewController
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
